package com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.invoice;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.adapter.ShoppingCartAdapter;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.bean.ReceiptBean;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.HUD;
import com.zzsy.carosshopprojects.util.PopupWindowUtils;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.view.WrapContentLinearLayoutManager;
import com.zzsy.carosshopprojects.view.dialog.ComTwnBtnReceiptDialog;
import com.zzsy.carosshopprojects.view.dialog.ComTwoBtnDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 开票列表
 */
public class ReceiptListFragment extends BaseFragment {
    @BindView(R.id.recyclerview)
    RecyclerView rcyView;
    @BindView(R.id.tv_member)
    TextView tvMemeber;
    @BindView(R.id.checkbox_all)
    CheckBox checkboxAll;
    @BindView(R.id.tv_checkbox_all)
    LinearLayout tv_checkbox_all;
    @BindView(R.id.btn_check_out)
    TextView btnCheckOut;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_select_money)
    TextView tvSelectMoney;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_card_type)
    TextView tvCardType;//卡类型
    @BindView(R.id.tv_status_fa)
    TextView tvStatusFa;//发票状态
    @BindView(R.id.ll_show)
    LinearLayout llShow;
    @BindView(R.id.ll_total)
    LinearLayout llTotal;
    @BindView(R.id.ll_check_all)
    LinearLayout llCheckAll;
    @BindView(R.id.ll_views)
    LinearLayout ll_views;
    private ReceiptListMode receiptListMode;
    private String timeOutStatus = "0";
    private String cardType = "0";
    private String totalMoney = "0";
    private List<ReceiptBean.UnInvoiceOrderDTOsBean> mReceiptList;
    private ShoppingCartAdapter shoppingCartAdapter;
    private ComTwoBtnDialog comTwnBtnDialog;
    private ComTwnBtnReceiptDialog comTwnBtnReceiptDialog;
    private String companyId;
    private String uuid;

    public static ReceiptListFragment newInstance(String uuid) {
        ReceiptListFragment receiptListFragment = new ReceiptListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("uuid", uuid);
        receiptListFragment.setArguments(bundle);
        return receiptListFragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fg_receiptlist;
    }

    @Override
    protected void initView(View view) {
        initTitle(view, getResources().getString(R.string.BillingList), getActivity());
    }

    @Override
    protected void initData(Context mContext) {
        receiptListMode = getViewModelProvider().get(ReceiptListMode.class);
        mReceiptList = new ArrayList<>();
        shoppingCartAdapter = new ShoppingCartAdapter(getContext(), mReceiptList, 0, checkboxAll, tv_checkbox_all, tvSelectMoney, tvCount);
        rcyView.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rcyView.setAdapter(shoppingCartAdapter);
        companyId = DataUtil.getInstance().getCompanyId();
        uuid = getArguments().getString("uuid");
    }

    @Override
    public void onResume() {
        super.onResume();
        PopupWindowUtils.closePopupwindow();
    }

    @Override
    protected void loadMethod() {
        getUUIDOrderData();
        showPrice();
        receiptListMode.getLiveCode().observe(this, integer -> {
            if (integer == 200) {
                startWithPop(ReceiptSufFragment.newInstance());
            }
        });
    }


    private void getUUIDOrderData() {
        receiptListMode.getLiveData().observe(this, receiptBean -> {
            if (receiptBean != null) {
//                if (receiptBean.getInvoiceSwitch().equals("0"))//0 需要发票功能 1 不需要
//                {
//                    tvMemeber.setVisibility(View.VISIBLE);
//                } else {
//                    tvMemeber.setVisibility(View.GONE);
//                }
                String invoiceAmount = receiptBean.getMemberInvoice();
                if (!StringUtils.isEmpty(invoiceAmount)) {
                    totalMoney = ConverterHelper.toBigDecimal(invoiceAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                } else {
                    totalMoney = "0";
                }
                mReceiptList.clear();
                if (receiptBean.getUnInvoiceOrderDTOs().size() > 0) {
                    mReceiptList.addAll(receiptBean.getUnInvoiceOrderDTOs());
                    rcyView.setVisibility(View.VISIBLE);
                    llShow.setVisibility(View.GONE);
                } else {
                    rcyView.setVisibility(View.GONE);
                    llShow.setVisibility(View.VISIBLE);
                }
                shoppingCartAdapter.notifyDataSetChanged();
                if (shoppingCartAdapter != null) {
                    shoppingCartAdapter.checkAll_none(false);
                    shoppingCartAdapter.checkAll();
                }
                setUI(totalMoney);
            } else {
                tvMemeber.setVisibility(View.GONE);
            }
        });
        receiptListMode.getUUIDOrderData(getContext(), cardType, timeOutStatus, uuid);
    }

    private void showPrice() {
        receiptListMode.getLive().observe(this, s -> {
            setUI(s);
        });
    }

    @OnClick({R.id.btn_check_out, R.id.tv_member, R.id.tv_card_type, R.id.tv_status_fa})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_check_out:
                showDialogs();
                break;
            case R.id.tv_member:
                showReceiptDialogs();
                break;
            case R.id.tv_card_type:
                showPopupwindow();
                break;
            case R.id.tv_status_fa:
                showPopupwindowStatus();
                break;
        }
    }

    private void setUI(String totalMoney) {
        this.totalMoney = totalMoney;
        tvTotal.setText("￥" + totalMoney);
    }

    private void showType(String cardType, String timeOutStatus) {
        if (!StringUtils.isEmpty(cardType)) {
            if ("0".equals(cardType)) {
                tvCardType.setText("全部订单");
            } else if ("1".equals(cardType)) {
                tvCardType.setText("该卡订单");
            } else if ("2".equals(cardType)) {
                tvCardType.setText("副卡订单");
            }
        }
        if (!StringUtils.isEmpty(timeOutStatus)) {
            if ("0".equals(timeOutStatus)) {
                tvStatusFa.setText("可开状态");
            } else if ("1".equals(timeOutStatus)) {
                tvStatusFa.setText("过期状态");
            }

        }
    }

    /**
     * 发票状态选择
     */
    private void showPopupwindowStatus() {

        View view = View.inflate(getContext(), R.layout.inflate_popup_status, null);
        ScreenAdapterTools.getInstance().loadView(view);
        View view1 = PopupWindowUtils.showPopupwindow(getContext(), view, ll_views);
        TextView tvStatusYes = view1.findViewById(R.id.tv_status_yes);
        LinearLayout ly_back = view1.findViewById(R.id.ly_back);
        tvStatusYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
                if (!StringUtils.isEmpty(uuid)) {
                    timeOutStatus = "0";
                    receiptListMode.getUUIDOrderData(getContext(), cardType, timeOutStatus, uuid);
                    llTotal.setVisibility(View.VISIBLE);
                    llCheckAll.setVisibility(View.VISIBLE);
                    showType(cardType, "0");
                }
            }
        });
        TextView tvStatusNo = view1.findViewById(R.id.tv_status_no);
        tvStatusNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
                if (!StringUtils.isEmpty(uuid)) {
                    timeOutStatus = "1";
                    receiptListMode.getUUIDOrderData(getContext(), cardType, timeOutStatus, uuid);
                    llTotal.setVisibility(View.GONE);
                    llCheckAll.setVisibility(View.GONE);
                    showType(cardType, "1");
                }
            }
        });
        ly_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
            }
        });

        if (timeOutStatus.equals("0")) {
            tvStatusYes.setTextColor(Color.parseColor("#FF6900"));
            tvStatusNo.setTextColor(Color.parseColor("#000000"));

        } else if (timeOutStatus.equals("1")) {
            tvStatusYes.setTextColor(Color.parseColor("#000000"));
            tvStatusNo.setTextColor(Color.parseColor("#FF6900"));
        }
    }

    /**
     * 展示卡的类型
     */
    private void showPopupwindow() {
        View view = View.inflate(getContext(), R.layout.inflate_popup, null);
        ScreenAdapterTools.getInstance().loadView(view);
        View view1 = PopupWindowUtils.showPopupwindow(getContext(), view, ll_views);
        TextView tvAllOrder = view1.findViewById(R.id.tv_all_order);
        LinearLayout ly_back = view1.findViewById(R.id.ly_back);
        tvAllOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
                if (!StringUtils.isEmpty(uuid)) {
                    cardType = "0";
                    receiptListMode.getUUIDOrderData(getContext(), cardType, timeOutStatus, uuid);
                    showType("0", timeOutStatus);
                }
            }
        });
        ly_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
            }
        });
        TextView tvNowOrder = view1.findViewById(R.id.tv_now_order);
        tvNowOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
                if (!StringUtils.isEmpty(uuid)) {
                    cardType = "1";
                    receiptListMode.getUUIDOrderData(getContext(), cardType, timeOutStatus, uuid);
                    showType("1", timeOutStatus);
                }
            }
        });
        TextView tvFuOrder = view1.findViewById(R.id.tv_fu_order);
        tvFuOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PopupWindowUtils.closePopupwindow();
                if (!StringUtils.isEmpty(uuid)) {
                    cardType = "2";
                    receiptListMode.getUUIDOrderData(getContext(), cardType, timeOutStatus, uuid);
                    showType("2", timeOutStatus);
                }
            }
        });
        if (cardType.equals("0")) {
            tvAllOrder.setTextColor(Color.parseColor("#FF6900"));
            tvNowOrder.setTextColor(Color.parseColor("#000000"));
            tvFuOrder.setTextColor(Color.parseColor("#000000"));
        } else if (cardType.equals("1")) {
            tvAllOrder.setTextColor(Color.parseColor("#000000"));
            tvNowOrder.setTextColor(Color.parseColor("#FF6900"));
            tvFuOrder.setTextColor(Color.parseColor("#000000"));
        } else if (cardType.equals("2")) {
            tvAllOrder.setTextColor(Color.parseColor("#000000"));
            tvNowOrder.setTextColor(Color.parseColor("#000000"));
            tvFuOrder.setTextColor(Color.parseColor("#FF6900"));
        }
    }


    /**
     * 自定义开具发票dialog
     */
    private void showReceiptDialogs() {
        if (comTwnBtnReceiptDialog != null) {
            comTwnBtnReceiptDialog.dismiss();
        }
        comTwnBtnReceiptDialog = new ComTwnBtnReceiptDialog(getActivity(), totalMoney);
        comTwnBtnReceiptDialog.show();
        comTwnBtnReceiptDialog.setDialogBtnClickListener(new ComTwnBtnReceiptDialog.IDialogBtnClickListener() {
            @Override
            public void onDialogLeftBtnClick() {
                comTwnBtnReceiptDialog.dismiss();
            }

            @Override
            public void onDialogRightBtnClick(String money) {
                if (StringUtils.isEmpty(money)) {
                    ToastUtils.showToast(getContext().getApplicationContext(), "请输入开票金额！");
                    return;
                }
                comTwnBtnReceiptDialog.dismiss();
                //调取自定义金额开票
                receiptListMode.getTokens(getContext(), money, uuid);
            }

        });
    }


    private void showDialogs() {
        if (comTwnBtnDialog != null) {
            comTwnBtnDialog.dismiss();
        }
        comTwnBtnDialog = new ComTwoBtnDialog(getActivity(), ComTwoBtnDialog.RECEIPT_LIST, null);
        comTwnBtnDialog.show();
        comTwnBtnDialog.setDialogBtnClickListener(new ComTwoBtnDialog.IDialogBtnClickListener() {
            @Override
            public void onDialogLeftBtnClick() {
                comTwnBtnDialog.dismiss();
            }

            @Override
            public void onDialogRightBtnClick() {
                // rcyView.setVisibility(View.GONE);
                HUD.getInstance().show(getContext(), "正在处理中...");
                String orderNums = "";
                for (int i = mReceiptList.size(), j = 0; i > j; i--) {
                    ReceiptBean.UnInvoiceOrderDTOsBean receiptBean = mReceiptList.get(i - 1);
                    if (receiptBean.isSelected()) {
                        mReceiptList.remove(receiptBean);
                        orderNums = orderNums + "," + receiptBean.getOrderNumber();
                    }
                }

                if (StringUtils.isEmpty(orderNums)) {
                    HUD.getInstance().dismiss();
                    ToastUtils.showToast(getContext().getApplicationContext(), "请选择相关数据！");
                    return;
                } else {
                    HUD.getInstance().dismiss();
                    String subStr = orderNums.substring(1, orderNums.length());
                    receiptListMode.getDrawBillTokens(getActivity(), subStr);
                }

                comTwnBtnDialog.dismiss();
            }
        });
    }


}
